package com.cangmaomao.m_mePen.fragment

import android.app.AlertDialog
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import com.cangmaomao.lib.base.BaseFragment
import com.cangmaomao.lib.utils.FileUtils.delFile
import com.cangmaomao.lib.utils.FileUtils.readFiles
import com.cangmaomao.m_mePen.R
import com.cangmaomao.m_mePen.adapter.SortListAdapter
import com.cangmaomao.m_mePen.bean.SortListBean
import com.cangmaomao.m_mePen.contract.FileListContract
import com.cangmaomao.m_mePen.event.FileList
import com.cangmaomao.m_mePen.presenter.FileListDetailsPresenter
import kotlinx.android.synthetic.main.f_sort_list.*
import org.greenrobot.eventbus.EventBus
import java.io.File
import java.util.*

class SortListFragment : BaseFragment<FileListContract.DetailsPresenter>(), SortListAdapter.OnShareClickListener,
        SortListAdapter.IsCollectClickListener, SortListAdapter.IsDeleteClickListener,
        View.OnClickListener, FileListContract.DetailsView {


    private val data = ArrayList<SortListBean>()
    private lateinit var adapter: SortListAdapter
    private var shareDialog: AlertDialog? = null
    private var deleteDialog: AlertDialog? = null
    private var title: String? = null
    private var isEdit: Boolean = false//是否编辑
    private var isAllChecked: Boolean = false//是否全选

    override val contentViewLayoutID: Int
        get() = R.layout.f_sort_list


    override fun readLocalFile(): Array<File> = readFiles(arguments!!.getString("name"))!!


    override fun showLocalFile(list: MutableList<SortListBean>) {
        data.addAll(list)
        adapter.notifyDataSetChanged()
    }


    /**
     * 检查数据是否有选中
     */
    private val isHaveChecked: Boolean
        get() {
            for (i in data.indices) {
                if (data[i].isDelete) {
                    return true
                }
            }
            return false
        }

    override fun initView(savedInstanceState: Bundle?) {
        deleteDialog = AlertDialog.Builder(mContext).create()
        shareDialog = AlertDialog.Builder(mContext).create()
        title = arguments!!.getString("name")
        initToolBarNav(title, getString(R.string.editData))
        val manager = LinearLayoutManager(mContext)
        recyclerView.layoutManager = manager
        allChecked!!.setOnClickListener(this)
        delete.setOnClickListener(this)

        adapter = SortListAdapter(mContext, data, this, this, this)
        adapter.setData(isEdit)
        recyclerView.adapter = adapter

        FileListDetailsPresenter(this)

        p.start()
    }


    override fun onRightClick() {
        isEdit = !isEdit
        if (isEdit) {
            initToolBarNav(title, getString(R.string.cancel))
            rl_Edit!!.visibility = View.VISIBLE
            updateLayoutParams(isEdit)
        } else {
            initToolBarNav(title, getString(R.string.editData))
            rl_Edit!!.visibility = View.GONE
            updateLayoutParams(isEdit)
        }
        adapter!!.setData(isEdit)
        adapter!!.notifyDataSetChanged()
        //初始化数据
        for (i in data.indices) {
            data[i].isDelete = false
        }
        isAllChecked = false
        setAllCheckedImg(R.drawable.icon_checked_unnormal)
    }

    /**
     * 编辑状态下更新布局
     */
    private fun updateLayoutParams(isEdit: Boolean) {
        val params = recyclerView!!.layoutParams as ViewGroup.MarginLayoutParams
        if (isEdit) {
            params.setMargins(0, dip2px(10f), 0, dip2px(60f))
        } else {
            params.setMargins(dip2px(20f), dip2px(10f), dip2px(20f), dip2px(10f))
        }
        recyclerView!!.requestLayout()
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    fun dip2px(dpValue: Float): Int {
        val scale = resources.displayMetrics.density
        return (dpValue * scale + 0.5f).toInt()
    }


    override fun onShare(position: Int) {
        val view = LayoutInflater.from(mContext).inflate(R.layout.dialog_collect_share, null)
        val imageView = view.findViewById<ImageView>(R.id.close)
        val shareWx = view.findViewById<TextView>(R.id.shareWx)
        val shareQQ = view.findViewById<TextView>(R.id.shareQQ)
        val shareFriend = view.findViewById<TextView>(R.id.shareFriend)
        imageView.setOnClickListener { v -> shareDialog!!.dismiss() }
        shareWx.setOnClickListener { v ->
            //微信
            Toast.makeText(mContext, "分享至微信", Toast.LENGTH_SHORT).show()
            shareDialog!!.dismiss()
        }
        shareQQ.setOnClickListener { v ->
            //qq
            Toast.makeText(mContext, "分享至QQ", Toast.LENGTH_SHORT).show()
            shareDialog!!.dismiss()
        }
        shareFriend.setOnClickListener { v ->
            //朋友圈
            Toast.makeText(mContext, "分享至朋友圈", Toast.LENGTH_SHORT).show()
            shareDialog!!.dismiss()
        }
        shareDialog!!.setView(view)
        shareDialog!!.show()
//        Objects.requireNonNull<Window>(shareDialog!!.window).setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))  // 有白色背景，加这句代码
    }

    override fun isCollect(position: Int) {
        if (data[position].isCollect) {
            Toast.makeText(mContext, "取消收藏", Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(mContext, "收藏成功", Toast.LENGTH_SHORT).show()
        }
        data[position].isCollect = !data[position].isCollect
        adapter!!.notifyDataSetChanged()
    }

    override fun isDelete(position: Int) {
        data[position].isDelete = !data[position].isDelete
        adapter!!.notifyDataSetChanged()
        if (isAllChecked()) {
            isAllChecked = true
            setAllCheckedImg(R.drawable.icon_checked_normal)
        } else {
            isAllChecked = false
            setAllCheckedImg(R.drawable.icon_checked_unnormal)
        }
    }

    /**
     * 检查数据是否全部选中
     */
    private fun isAllChecked(): Boolean {
        for (i in data.indices) {
            if (!data[i].isDelete) {
                return false
            }
        }
        return true
    }

    override fun onClick(v: View) {
        val i1 = v.id
        if (i1 == R.id.allChecked) {
            if (isAllChecked) {
                for (i in data.indices) {
                    data[i].isDelete = false
                }
                setAllCheckedImg(R.drawable.icon_checked_unnormal)
            } else {
                for (i in data.indices) {
                    data[i].isDelete = true
                }
                setAllCheckedImg(R.drawable.icon_checked_normal)
            }
            isAllChecked = !isAllChecked
            adapter!!.notifyDataSetChanged()
        } else if (i1 == R.id.delete) {
            if (isHaveChecked) {
                deleteData()
            } else {
                Toast.makeText(mContext, "请选择需要删除的文件", Toast.LENGTH_SHORT).show()
            }
        }
    }

    /**
     * 删除选中数据
     */
    private fun deleteData() {
        val view = LayoutInflater.from(mContext).inflate(R.layout.dialog_delete, null)
        val imageView = view.findViewById<ImageView>(R.id.close)
        val textView = view.findViewById<TextView>(R.id.sure)
        imageView.setOnClickListener { v -> deleteDialog!!.dismiss() }
        textView.setOnClickListener { v ->
            for (i in data.indices.reversed()) {
                if (data[i].isDelete) {
                    delFile(data[i].imgUrl)
                    data.removeAt(i)
                }
            }
            EventBus.getDefault().post(FileList(data.size, arguments!!.getString("pos").toInt()))
            adapter.notifyDataSetChanged()
            if (data.size == 0) {
                pop()
            }
            deleteDialog!!.dismiss()
        }
        deleteDialog!!.setView(view)
        deleteDialog!!.show()
//        Objects.requireNonNull<Window>(deleteDialog!!.window).setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))  // 有白色背景，加这句代码
    }

    /**
     * 设置全选或取消图片
     */
    private fun setAllCheckedImg(imgResources: Int) {
        val drawable = resources.getDrawable(imgResources)
        drawable.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
        allChecked!!.setCompoundDrawables(drawable, null, null, null)
    }
}
